package com.bh.kysys.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bh.common.annotation.DataDictClass;
import com.bh.common.constant.CacheConstants;
import com.bh.common.constant.Symbol;
import com.bh.common.exception.base.BaseException;
import com.bh.common.utils.MapUtils;
import com.bh.common.utils.StringUtils;
import com.bh.kysys.domain.JcZone;
import com.bh.kysys.mapper.JcZoneMapper;
import com.bh.kysys.service.IJcZoneService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 行政区域Service业务层处理
 *
 * @author slx
 * @date 2023-03-24
 */
@Service
public class JcZoneServiceImpl extends ServiceImpl<JcZoneMapper, JcZone> implements IJcZoneService {
    @Autowired
    private JcZoneMapper jcZoneMapper;

    /**
     * 查询行政区域
     *
     * @param id 行政区域主键
     * @return 行政区域
     */
    @Cacheable(cacheNames = CacheConstants.CACHE_ZONE, key = "#id")
    @DataDictClass
    @Override
    public JcZone selectJcZoneById(Long id) {
        return jcZoneMapper.selectById(id);
    }

    @Override
    public String selectJcZoneNamesByIds(String[] ids) {
        List<JcZone> zones = jcZoneMapper.selectBatchIds(Arrays.asList(ids));
        return zones.stream().map(JcZone::getName).collect(Collectors.joining(","));
    }


    @Override
    public List<JcZone> selectJcZoneList(JcZone zoneParam) {
        List<JcZone> zones = jcZoneMapper.selectJcZoneList(zoneParam);
        if (zones == null || zones.size() == 0) {
            return zones;
        }
        Long[] ids = zones.stream().map(JcZone::getId).toArray(Long[]::new);
        Map<String, HashMap<String, Long>> map = jcZoneMapper.selectIsTreeLeafByZids(ids);
        for (JcZone zone : zones) {
            if (map.get(zone.getId()) != null && map.get(zone.getId()).get("number") != null) {
                zone.setHasChildren(map.get(zone.getId()).get("number") > 0);
            }

        }
        return zones;
    }

    @Override
    public List<JcZone> selectJcZoneListByZid(Long zid) {
        List<JcZone> zones = jcZoneMapper.selectJcZoneListByZid(zid);
        if (zones == null || zones.size() == 0) {
            return zones;
        }
        Long[] ids = zones.stream().map(JcZone::getId).toArray(Long[]::new);
        Map<String, HashMap<String, Long>> map = jcZoneMapper.selectIsTreeLeafByZids(ids);
        for (JcZone zone : zones) {
            if (map.get(zone.getId()) != null && map.get(zone.getId()).get("number") != null) {
                zone.setHasChildren(map.get(zone.getId()).get("number") > 0);
            }

        }
        return zones;
    }

    /**
     * 新增行政区域
     *
     * @param jcZone 行政区域
     * @return 结果
     */
    @CacheEvict(cacheNames = CacheConstants.CACHE_ZONE, key = "'*'")
    @Override
    public int insertJcZone(JcZone jcZone) {
        return jcZoneMapper.insert(jcZone);
    }

    /**
     * 修改行政区域
     *
     * @param jcZone 行政区域
     * @return 结果
     */
    @CacheEvict(cacheNames = CacheConstants.CACHE_ZONE, key = "'*'")
    @Override
    public int updateJcZone(JcZone jcZone) {
        return jcZoneMapper.updateById(jcZone);
    }

    /**
     * 批量删除行政区域
     *
     * @param ids 需要删除的行政区域主键
     * @return 结果
     */
    @CacheEvict(cacheNames = CacheConstants.CACHE_ZONE, key = "'*'")
    @Override
    public int deleteJcZoneByIds(String[] ids) {
        return jcZoneMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除行政区域信息
     *
     * @param id 行政区域主键
     * @return 结果
     */
    @CacheEvict(cacheNames = CacheConstants.CACHE_ZONE, key = "'*'")
    @Override
    public int deleteJcZoneById(Long id) {
        return jcZoneMapper.deleteById(id);
    }

    @Override
    public Map<String, String> selectJcZoneByZoneNames(String zoneNames) {
        if (StringUtils.isNotBlank(zoneNames)) {
            Map<String, String> map = new HashMap<>();
            List<JcZone> fullZones = new ArrayList<>();
            String[] zoneNamesArr = zoneNames.split(Symbol.COMMA);
            List<JcZone> zones = jcZoneMapper.selectJcZoneByName(zoneNamesArr[0]);
            if (zones == null || zones.size() != 1) {
                throw new BaseException("行政区划名称[" + zoneNames + "]错误，请查询系统内行政区划表！");
            }
            JcZone firstZone = zones.getFirst();
            // 查询上层
            if (firstZone.getZid() != 0) {
                JcZone parentZone = jcZoneMapper.selectById(firstZone.getZid());
                while (parentZone != null && parentZone.getZid() != 0) {
                    fullZones.addFirst(parentZone);
                    parentZone = jcZoneMapper.selectById(parentZone.getZid());
                }
            }
            fullZones.add(firstZone);
            // 查询子节点
            for (int i = 0; i < zoneNamesArr.length; i++) {
                if (i == 0) {
                    continue;
                }
                String s = zoneNamesArr[i];
                JcZone jcZone = jcZoneMapper.selectJcZoneByNameAndZid(s, firstZone.getId());
                if (jcZone == null) {
                    throw new BaseException("行政区划名称[" + zoneNames + "]错误，请查询系统内行政区划表！");
                }
                firstZone = jcZone;
                fullZones.add(jcZone);
            }
            if (!fullZones.isEmpty()) {
                map.put("lastZoneId", fullZones.getLast().getId().toString());
                map.put("fullZoneId", fullZones.stream().map(JcZone::getId).map(String::valueOf).collect(Collectors.joining(",")));
                map.put("fullZoneName", fullZones.stream().map(JcZone::getName).collect(Collectors.joining(",")));
                return map;
            }
        }
        return null;
    }
}
